package org.club.common.exception;


import org.club.common.model.entity.BusinessException;
import org.club.common.util.ApiResponseMe;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局异常处理器
 * 用于统一处理项目中的异常，提高代码的健壮性和可维护性
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ApiResponseMe> handleBusinessException(BusinessException e) {
        ApiResponseMe response = new ApiResponseMe();
        response.setCode(e.getCode());
        response.setMessage(e.getMessage());
        response.setData(null);

        // 根据业务异常的状态码设置HTTP状态码
        HttpStatus status = e.getCode() >= 500 ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.OK;
        return new ResponseEntity<>(response,status);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponseMe> handleException(Exception e) {
        ApiResponseMe response = new ApiResponseMe();
        response.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setMessage("内部服务器错误");
        response.setData(null);
        e.printStackTrace(); // 打印异常堆栈以便日志记录
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
